﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;

namespace Wrench.Management
{
    public partial class UploadPortfolio : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ClearHeaders();
            Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
            Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
            Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
            Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
            Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 
            Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 
            Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 
            Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1 
            Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1 
            Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1 

            Response.Clear();
            Response.ContentType = "text/plain";
            try
            {
                String fileName = Request.Files[0].FileName;
                Stream fileStream = Request.Files[0].InputStream;
                String extension = fileName.Substring(fileName.LastIndexOf('.'));//扩展名
                String imageURL = this.UploadImage(fileName, fileStream);

                if (String.IsNullOrEmpty(imageURL))
                {
                    throw new Exception("Invoke image upload services exception.");
                }


                Response.Write("{\"Status\": \"Success\", \"FileName\": \"" + fileName + "\",\"Extension\": \"" + extension + "\", \"ImageURL\": \"" + imageURL + "\"}");
            }
            catch (Exception ex)
            {
                Response.Write("{\"Status\": \"Error\", \"Exception\": \"" + ex.Message + "\"}");
            }
            Response.End();
        }
        /// <summary>
        /// UploadHomePageImage
        /// </summary>
        /// <param name="originalFileName">Client file name</param>
        /// <param name="image">image stream</param>
        /// <returns></returns>
        public string UploadImage(String originalFileName, Stream image)
        {

            //生成原图
            Byte[] oFileByte = new byte[2048];
            // System.IO.Stream oStream = this.UploadFile.PostedFile.InputStream;
            System.Drawing.Image oImage = System.Drawing.Image.FromStream(image);

            int oWidth = oImage.Width; //原图宽度
            int oHeight = oImage.Height; //原图高度
            int tWidth = 400; //设置缩略图初始宽度
            int tHeight = 400; //设置缩略图初始高度

            //按比例计算出缩略图的宽度和高度
            if (oWidth >= oHeight)
            {
                tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oWidth)));
            }
            else
            {
                tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
            }

            //生成缩略原图
            Bitmap tImage = new Bitmap(tWidth, tHeight);
            Graphics g = Graphics.FromImage(tImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量插值法
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
            g.Clear(Color.Transparent); //清空画布并以透明背景色填充
            g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);

            string oFullName = Server.MapPath("~/UpLoad/Portfolio/") + "o" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg"; //保存原图的物理路径
            string tFullName = Server.MapPath("~/UpLoad/Portfolio/") + "t" + DateTime.Now.ToShortDateString().Replace("-", "") + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + ".jpg"; //保存缩略图的物理路径

            try
            {
                //以JPG格式保存图片
                oImage.Save(oFullName, System.Drawing.Imaging.ImageFormat.Jpeg);
                tImage.Save(tFullName, System.Drawing.Imaging.ImageFormat.Jpeg);


                // string savepic = getname(tFullName); //获取新文件名
                FileInfo ff = new FileInfo(tFullName);
                string newp = ff.Name;

                //string savetu = Server.MapPath("~/UpLoad/Portfolio/" + newp);  //路径



                return newp;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //释放资源
                oImage.Dispose();
                g.Dispose();
                tImage.Dispose();
            }







            //String m_Result = Guid.NewGuid().ToString("D") +"jpg";
            ////FileServiceSoapClient m_FileServiceSoapClient = new FileServiceSoapClient();
            ////MemoryStream m = new MemoryStream();
            //FileStream fs = File.Open(Server.MapPath("~/UpLoad/Portfolio/") + m_Result, FileMode.OpenOrCreate);
            //try
            //{
            //    int size = 2048;
            //    byte[] data = new byte[2048];

            //    while (true)
            //    {
            //        // 写入数据
            //        size = image.Read(data, 0, data.Length);
            //        if (size > 0)
            //        {
            //            fs.Write(data, 0, size);
            //        }
            //        else
            //        {
            //            break;
            //        }
            //    }

            //    return m_Result;

            //}
            //catch (Exception)
            //{
            //    image.Close();
            //    image.Dispose();

            //    return String.Empty;
            //}
            //finally
            //{
            //    fs.Close();
            //    fs.Dispose();
            //}

        }
        public string getname(string name)
        {
            Random rm = new Random();
            string newname = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString()
                + DateTime.Now.Second.ToString() + rm.Next(1000) + name.Substring(name.LastIndexOf("."), name.Length - name.LastIndexOf("."));
            return newname;
        }
    }
}
